using Godot;
using System;

public partial class BatEnemy : CharacterBody2D
{
    [Export]
    public int range = 120;

    private int SPEED = 30;

    private Sprite2D sprite2D;

    private AnimationTree animationTree;

    private AnimationNodeStateMachinePlayback playback;

    private RayCast2D rayCast2D;

    private Hurtbox hurtbox;

    public override void _Ready()
    {
        sprite2D = GetNode<Sprite2D>("Sprite2D");

        animationTree = GetNode<AnimationTree>("AnimationTree");
        playback = (AnimationNodeStateMachinePlayback)animationTree.Get("parameters/StateMachine/playback");

        rayCast2D = GetNode<RayCast2D>("RayCast2D");

        hurtbox = GetNode<Hurtbox>("Hurtbox");
        hurtbox.Hurt += (Hitbox otherHitbox) => { QueueFree(); };
    }

    public override void _PhysicsProcess(double delta)
    {
        string curNode = playback.GetCurrentNode();

        switch (curNode)
        {
            case "Idle":
                break;
            case "Chase":
                Player p = GetPlayer();
                if (p != null)
                {
                    Velocity = GlobalPosition.DirectionTo(p.GlobalPosition) * SPEED;
                    sprite2D.Scale = new Vector2(Mathf.Sign(Velocity.X), 1);
                }
                else
                {
                    Velocity = Vector2.Zero;
                }
                MoveAndSlide();
                break;
        }
    }

    private Player GetPlayer()
    {
        return GetTree().GetFirstNodeInGroup("player") as Player;
    }

    public bool IsPlayInRange()
    {
        bool res = false;
        Player p = GetPlayer();
        if (p != null)
        {
            return GlobalPosition.DistanceTo(p.GlobalPosition) < range;
        }
        return res;
    }

    public bool CanSeePlayer()
    {
        if (!IsPlayInRange()) return false;

        Player p = GetPlayer();
        rayCast2D.TargetPosition = p.GlobalPosition - GlobalPosition;
        return !rayCast2D.IsColliding();
    }

}
